<?php

namespace app\api\controller\v1;

use app\api\model\Product as ProductModel;
use app\api\model\SkuSpecs as SkuSpecsModel;
use app\api\validate\Count;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\Paginate;
use app\common\exception\MissException;
use think\Request;

class Product extends Base
{
    public function getDetailByID($id)
    {
        (new IDMustBePositiveInt())->goCheck();
        $id = Request::instance()->param('id', 1);
        $product = ProductModel::getDetailByID($id);
        if(empty($product)){
            throw new MissException([
                'msg' => "没找到编号为{$id}的商品"
            ]);
        }

        $data = SkuSpecsModel::where('product_id', '=', $id)->select()->toArray();

        $temp = [
            [
                'name'=>'颜色',
                'item'=>[
                    [
                        'name'=>'红色'
                    ],
                    [
                        'name'=>'白色'
                    ]
                ]
            ],
            [
                'name'=>'容量',
                'item'=>[
                    [
                        'name'=>'64GB'
                    ],
                    [
                        'name'=>'128GB'
                    ]
                ]
            ]
        ];
        $product['specs'] = $data;
        return $this->ok($product);
    }

    public function getListByCategoryID($id)
    {
        (new IDMustBePositiveInt())->goCheck();
//        $id = $this->request->param('id', 1);
//        $product = ProductModel::where('root_category_id', '=', $id)->with('sku')->select();
        $products = ProductModel::getDetailByCategoryID($id);
        if($products->isEmpty())
        {
            throw new MissException([
                'msg' => "{$id}号的分类下没有商品"
            ]);
        }
        return $this->ok($products);
    }

    public function getLatest($size = 3)
    {
        (new Count())->goCheck();
        $products = ProductModel::getRecent($size);
        if($products->isEmpty())
        {
            throw new MissException([
                'msg' => "最近没有上架商品"
            ]);
        }
        $products = $products->hidden(['subtitle']);
        return $this->ok($products);
    }

    public function getAll($page=1, $size=15)
    {
        (new Paginate())->goCheck();
        $pager = ProductModel::getAll($page, $size);
        if ($pager->isEmpty()) {
            throw new MissException([
                'msg' => "没找到商品分类数据"
            ]);
        }
        return $this->ok($pager);
    }
}